<template lang="pug">
div(style="padding-bottom: 2.5rem")
  app-header(fixed,title="购物车",v-if="!$helper.isWechat")
  div.content-pad(:style="{top: $helper.isWechat ? '0' : '0.84rem'}")
    section.cart_nodata(v-if="!cart.length")
      p 购物车还空着呢，赶快选材料加入购物车吧！
      mt-button(size="large",type="danger",@click="$router.push({name: 'sorts:index', params: {id: 0}})") 选材料
    section(v-else)
      div(ref="mainWrapper",class="main-wrapper")
        ul
          li.product-item(v-for="(item,index) in cart",:key="index")
            label(@click="toggleCart({id: item.id})")
              b(:class="item.checked ? 'checked' : ''") &radic;
            .icon
              img(:src="_.get(item, 'model.icon')")
            .content
              h2.name {{ getModelName(item) }}
              .price
                span 价格*数量: {{ getModelPrice(item) }} 元  x {{ _.get(item, 'order.count') }}
              .total
                span 总价: {{ (getModelPrice(item) * _.get(item, 'order.count')).toFixed(2) }} 元
              .counter
                button(@click="minusCart({id: item.id})") -
                input(type="number",readonly,:value="_.get(item, 'order.count', 0)")
                button(@click="addCart({id: item.id})") +
              .remove
                button(@click="removeCart({id: item.id})") x
      .check-out
        span 总价格: {{totalPrice}}&nbsp;&nbsp;&nbsp;&nbsp;数量: {{totalCount}}
        button(@click="submitHandler") 确认购买 
  mt-popup.address-box(v-model="popupVisible",position="right")
    h4 请选择送货地址
    ul
      li(v-for="item in address",@click="submitPayment(item.id)")
        strong {{item.user_name}}
        span {{item.city_name + item.detail_info}}
        span {{item.tel_number}}
  app-footer(active="cart",@handler="footerHandler")
</template>

<script>
import BScroll from 'better-scroll'
import { Button, Popup, Toast, MessageBox } from 'mint-ui'
import Footer from 'components/Footer'
import Header from 'components/Header'
import { mapActions, mapGetters } from 'vuex'
import axios from 'axios'

export default {
  components: {
    'mt-button': Button,
    'mt-popup': Popup,
    'app-footer': Footer,
    'app-header': Header
  },
  computed: {
    ...mapGetters({
      cart: 'getCart',
      profile: 'getProfile'
    }),
    totalPrice: {
      get () {
        let n = 0
        for (let item of this.cart) {
          if (item.checked) {
            n += this.getModelPrice(item) * item.order.count
          }
        }
        return n.toFixed(2)
      }
    },
    totalCount: {
      get () {
        let n = 0
        for (let item of this.cart) {
          if (item.checked) {
            n += item.order.count
          }
        }
        return n
      }
    }
  },
  data () {
    return {
      popupVisible: false,
      address: [],
      orders: [],
      mainScroll: null,
      scrolling: false,
      paying: false
    }
  },
  watch: {
    cart: {
      handler (curVal, oldVal) {
        if (curVal.length) {
          this._initScroll()
        }
      },
      immediate: true
    }
  },
  methods: {
    ...mapActions({
      addCart: 'addCart',
      minusCart: 'minusCart',
      removeCart: 'removeCart',
      toggleCart: 'toggleCart',
      clearCart: 'clearCart'
    }),
    getModelName (item) {
      let models = this._.get(item, 'model.models', [])
      let id = this._.get(item, 'order.modelId')
      for (let obj of models) {
        if (obj.id === id) {
          return this._.get(item, 'model.title') + '[' + obj.title + ']'
        }
      }
      return '-'
    },
    getModelPrice (item) {
      let models = this._.get(item, 'model.models', [])
      let id = this._.get(item, 'order.modelId')
      for (let obj of models) {
        if (obj.id === id) {
          return obj.price
        }
      }
      return '-1'
    },
    async loadAddressLists () {
      const result = await this.$rpc.invoke('address_lists', []).complete()
      if (result.code) {
        Toast(result.message)
        return false
      }
      this.address = result.data
      if (this.address.length < 1) {
        let instance = Toast('请添加一个收获地址')
        window.setTimeout(() => {
          instance.close()
          this.$router.push({name: 'user:address'})
        }, 2000)
        return false
      }
      return true
    },
    _initScroll () {
      if (!this.mainScroll) {
        this.$nextTick(() => {
          this.mainScroll = new BScroll(this.$refs.mainWrapper, {
            probeType: 1,
            click: true,
            scrollbar: {
              fade: true,
              interactive: false
            }
          })
        })
      } else {
        this.mainScroll.refresh()
      }
    },
    footerHandler (type) {
      this.$router.push({name: type + ':index'})
    },
    async submitPayment (addressId) {
      this.popupVisible = false
      // - 获得支付配置
      const url = this._.config['urls']['wx_generat_order']
      let params = new URLSearchParams()
      params.append('address_id', addressId)
      params.append('orders', JSON.stringify(this.orders))
      params.append('token', this.profile ? this.profile.token : null)
      params.append('pay_type', this.$helper.isWechat ? 'wechat' : 'web')
      let result = (await axios.post(url, params)).data
      if (parseInt(result.state) === 0 || parseInt(result.state) === 406) {
        this.clearCart()
        this.$router.push({ name: 'order:lists', params: {type: 'all'} })
      }
      if (result.state) {
        return Toast(result.message)
      }
      // 开始微信支付
      let orderInfo = this._.get(result, 'data.info')
      let isVip = this._.get(orderInfo, 'is_vip')
      let count = this._.get(orderInfo, 'count')
      let originalPrice = this._.get(orderInfo, 'original_price')
      let price = this._.get(orderInfo, 'price')

      let msg = '数量: ' + count + ','
      if (isVip) {
        msg += '原价:' + originalPrice + '打折后价格:' + price
      } else {
        msg += '价格:' + price
      }
      msg += ', 是否确认支付?'
      let action = await MessageBox.confirm(msg)
      if (action !== 'confirm') {
        return
      }
      // - 调起支付
      let orderConfig = this._.get(result, 'data.config')
      if (this.paying) {
        return Toast('正在调起支付,请稍后..')
      } else {
        orderConfig['success'] = (res) => {
          if (res.errMsg !== 'chooseWXPay:ok') {
            Toast(res.errMsg)
          }
          this.paying = false
        }
        orderConfig['cancel'] = orderConfig['fail'] = (res) => {
          console.log('调起微信支付失败', res)
          this.paying = false
        }
        this.paying = true
        window.wx.chooseWXPay(orderConfig)
      }
    },
    async submitHandler () {
      this.orders = []
      for (let item of this.cart) {
        if (!item.checked || (item.order && item.order.count < 1)) {
          continue
        }
        this.orders.push(item.order)
      }
      let bool = await this.loadAddressLists()
      if (!bool) {
        return
      }
      this.popupVisible = true
    }
  }
}
</script>
<style lang="stylus" scoped>
.address-box
  position: absolute
  left: 0
  right: 0
  display: block
  padding: .5rem
  h4
    margin-bottom: .3rem
    border-bottom: 1px solid #ccc
    color: #666
    font-weight: normal
  li
    border-bottom: 1px solid #efefef
    cursor: pointer
    padding: .4rem 0
    list-style: none
    strong,span
      padding: 0 .1rem
.product-item
  position: relative
  display: flex
  text-align: left
  width: 100%
  border-bottom: .0025rem solid #eee
  label
    b
      display: inline-block
      width: .45rem
      height: .45rem
      margin-left: .2rem
      margin-top: .26rem
      border: 1px solid #ccc
      cursor: pointer
      border-radius: 50%
      vertical-align: middle
      color: #fff
      text-align: center
      font-size: .3rem
      line-height: .54rem
    b.checked
      background: #ff4344
      border: none
  .icon
    flex: 0 0 2.5625rem
    margin: .225rem
    width: 1.5625rem
    height: 2.3625rem
    background-color: #ccc
    border-radius: .1rem
    overflow: hidden
    img
      width: 100%
      height: 100%
  .content
    flex: 1
    color: #666
    .name
      margin: .125rem 0 .1rem 0
      font-size: .375rem 
      line-height: .55rem
      color: rgba(7, 17, 27, .7)
      cursor: pointer
    .price,.total
      line-height: .6rem
      .now
        font-size: .475rem
        color: rgb(240, 20, 20)
      .old
        font-size: .425rem
        color: rgb(147, 153, 159)
        text-decoration: line-through
    .counter
      position: absolute
      left: 3.7rem
      bottom: .1rem
      button
        border: none
        outline: none
        border: 1px solid #eee
        border-radius: 50%
        padding: .06rem .16rem
        cursor: pointer
        text-align: center
        color: #333
        background: #fff
      input
        width: .9rem
        height: .7rem
        margin: 0 .1rem
        text-align: center
        border-radius: .1rem
        border: 1px solid #eee
    .remove
      position: absolute
      left: 6.2rem
      bottom: .2rem
      button
        border: none
        outline: none
        border: 1px solid #eee
        color: #333
        border-radius: 50%
        padding: .06rem .16rem
        cursor: pointer
        text-align: center
        background: #fff
.cart_nodata
  padding: 1.28rem .32rem 0
  p
    line-height: 0.8rem
    text-align: center
    margin-bottom: 2rem
    font-size: .28rem
  &:before
    content: ''
    display: block
    width: 1.96rem
    height: 2.12rem
    background-position: 0 -9rem
    margin: 0 auto .3733rem
.main-wrapper
  position: relative
  top: 0
  left: 0
  right: 0
  bottom: 1.2rem
  overflow: hidden
.check-out
  border-top: 1px solid #ddd
  background: #efefef
  position: absolute
  left: 0
  right: 0
  bottom: 1.3rem
  height: 1.4rem
  span
    padding: .1rem .1rem
    font-size: .36rem
    float: left
    margin: .2rem 0 0 .4rem
  button
    float: right
    margin: .2rem 1rem 0 0
    font-size: .36rem
    padding: .1rem .4rem
    background: orange
    color: #fff
    border: none
    border-radius: .15rem
    outline: none
    cursor: pointer
</style>
